<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=, initial-scale=1.0">
    <title>二分查找</title>
    <script type="text/javascript">
    var i=0;
     function binary_search2(arr, low, high, key) {
	if(low<=high) {
	var mid = parseInt((high + low) / 2);        
		if(arr[mid] == key) 
               { i++;
                document.getElementById('show1').innerHTML ="第"+i+"次查询";
                document.getElementById('show2').innerHTML ="low: a["+low+"]";
                document.getElementById('show3').innerHTML ="mid: a["+mid+"]";
                document.getElementById('show4').innerHTML ="high: a["+high+"]";
                return mid;
               }    
	    else 
            if(arr[mid] > key){i++;
                  document.getElementById('show5').innerHTML ="第"+i+"次查询";
                  document.getElementById('show6').innerHTML ="low: a["+low+"]";
                  document.getElementById('show7').innerHTML ="mid: a["+mid+"]";
                  document.getElementById('show8').innerHTML ="high: a["+high+"]";
		          return binary_search2(arr, low, mid-1, key);
            }   
	        else
            {     i++;
                  document.getElementById('show9').innerHTML ="第"+i+"次查询";
                  document.getElementById('show10').innerHTML ="low: a["+low+"]";
                  document.getElementById('show11').innerHTML ="mid: a["+mid+"]";
                  document.getElementById('show12').innerHTML ="high: a["+high+"]";
                  return binary_search2(arr, mid+1, high, key);
            }    
    }            
    else         
        return -1;                  
}
</script>
</head>
<body>
<p>请输入数组：（实例如1，2，3，4，5，6，7，8，9，10）</p>
<input type="text" autocomplete="on" id="enter" style/> 
<p>请输入要查询的数字:</p>
<input type="text" autocomplete="on" id="search" style/> 
<button id="click">查找<button>
<div id="result" style=></div>
<div id=show1></div>
<div id=show2></div>
<div id=show3></div>
<div id=show4></div>
<div id=show5></div>
<div id=show6></div>
<div id=show7></div>
<div id=show8></div>
<div id=show9></div>
<div id=show10></div>
<div id=show11></div>
<div id=show12></div>
<script type="text/javascript">
document.getElementById('click').onclick = function(event) {
var arr = stringToArray(document.getElementById('enter').value);
var k = parseFloat(document.getElementById('search').value);
var result2 = binary_search2(arr, 0, arr.length-1, k)+1;
if(result2>=0)
    document.getElementById('result').innerHTML ="该数在数组第"+result2+"个位置";
else
    document.getElementById('result').innerHTML ="没有在数组中找到该数";
};
function stringToArray(str) {
    var array = [];
    var arr = str.split(',');
    for(var i = 0; i<arr.length; i++) {
    array.push(parseFloat(arr[i]));
    }
    return array;
    }
</script>
</body>
</html>